package com.ilovepostcard.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.Toast;

import com.ilovepostcard.PreviewActivity;
import com.ilovepostcard.R;
import com.ilovepostcard.SharekActivity;
import com.ilovepostcard.controller.server.IServer;
import com.ilovepostcard.controller.server.PostcardResult;
import com.ilovepostcard.controller.server.ServerFactory;
import com.ilovepostcard.data.OffLinePostcard;
import com.ilovepostcard.data.Postcard;
import com.ilovepostcard.utils.Constants;
import com.ilovepostcard.utils.Utils;

public class OffLineManager {
	
	static OffLineManager instance;
	final static String OffLineRoot = Constants.APP_DIR+"offline/";
	final static String OFFLINEDB = "offline_status";
	
	final static String KEY_NAME = "name";
	final static String KEY_STATUS="isfinish";
	final static String KEY_PAGE="pageIndex";
		
	OffLinePostcard mCurrentBackupPC;
	public static OffLineManager getInstance()
	{
		if(instance == null)
			instance = new OffLineManager();
		return instance;
	}
	public int getOffLineCount()
	{
		File root = new File(OffLineRoot);
		if(!root.exists()) return 0;
		
		File[] childs =root.listFiles();
		
		if(childs == null) return 0;
		return childs.length;
	}
	
	public OffLinePostcard getOffLineByName(String name)
	{
		File root = new File(OffLineRoot);
		if(!root.exists()) return null;
		
		File[] childs =root.listFiles();

		for(int i =0; i< childs.length;i++)
		{
			if(name.equals(childs[i].getName()))
			{
				OffLinePostcard pc = new OffLinePostcard(name);
				return pc;
			}

		}
		
		return null;
	}
	public OffLinePostcard[] getAllOffLinePostcard()
	{
		File root = new File(OffLineRoot);
		if(!root.exists()) return null;
		
		File[] childs =root.listFiles();
		
		
		ArrayList<OffLinePostcard> array = new ArrayList<OffLinePostcard>();
		for(int i =0; i< childs.length;i++)
		{
			String imageFile = childs[i].getAbsolutePath()+"/"+"image.jpg";
			String confFile = childs[i].getAbsolutePath()+"/"+"info.xml";
			File image = new File(imageFile);
			File config = new File(confFile);
			if(image.exists() && config.exists())
				//list[i] = new OffLinePostcard(childs[i].getName());
				array.add(new OffLinePostcard(childs[i].getName()));
			else
				delete(childs[i].getName());
		}
		
		array.trimToSize();
		OffLinePostcard[] list = new OffLinePostcard[array.size()];
		list = array.toArray(list);
		return list;
	}
	
	public void createBackupPC()
	{
		mCurrentBackupPC = new OffLinePostcard();
	}
	
	public OffLinePostcard getCurrentBackupPC()
	{
		return mCurrentBackupPC;
	}
	
	public void deleteAll()
	{
		File root = new File(OffLineRoot);
		if(!root.exists()) return;
		
		File[] childs =root.listFiles();

		for(int i =0; i< childs.length;i++)
		{
			deleteFolder(childs[i]);

		}
	}
	
	public boolean delete(String name)
	{
		File root = new File(OffLineRoot);
		if(!root.exists()) return true;
		
		File[] childs =root.listFiles();

		for(int i =0; i< childs.length;i++)
		{
			if(name.equals(childs[i].getName()))
			{
				return deleteFolder(childs[i]);
			}

		}
		
		return true;
	}
	
	public void updateOffLinePc(Context context,String name,int page)
	{
		SharedPreferences settings = context.getSharedPreferences(OFFLINEDB, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString(KEY_NAME, name);
        editor.putInt(KEY_PAGE, page);
        editor.commit();
	}
	
	public String getResumePC(Context context)
	{
		SharedPreferences settings = context.getSharedPreferences(OFFLINEDB, Context.MODE_PRIVATE);
		return settings.getString(KEY_NAME, null);
        
	}
	
	public int getResumePage(Context context)
	{
		SharedPreferences settings = context.getSharedPreferences(OFFLINEDB, Context.MODE_PRIVATE);
		return settings.getInt(KEY_PAGE, -1);
	}
	
	public void clearResumeInfo(Context context)
	{
		SharedPreferences settings = context.getSharedPreferences(OFFLINEDB, Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = settings.edit();
        editor.clear();
        editor.commit();
	}

	private boolean deleteFolder(File folder) {
		File[] files = folder.listFiles();
		for(File file : files) {
			if(file.isDirectory())
				deleteFolder(file);
			else
				file.delete();
		}
		return folder.delete();
	}
	public void finishCurrentbackupPC(Context context)
	{
		mCurrentBackupPC = null;
		clearResumeInfo(context);
		//FIXME
		//need save the information of postcard status such as whether edit finish
	}
	
	
	public PostcardResult uploadOffLinePc(Context c,String name)
	{
		
		OffLinePostcard olPc = new OffLinePostcard(name);
		PostcardResult result ;
		Postcard pc =  new Postcard();
		BitmapFactory.Options options = Utils.getBitmapInfo(new File(olPc.getImagePath()));
		pc.comment = olPc.get(OffLinePostcard.TAG_COMMENT);
		pc.location = olPc.get(OffLinePostcard.TAG_LOCATION);
		String found = olPc.get(OffLinePostcard.TAG_CANBEFOUND);
		String show = olPc.get(OffLinePostcard.TAG_SHOWLOCATION);
		pc.canBeFoundFlag = ((found == null) || (found.equals("false"))) ? 0 : 1;
		pc.showLocationFlag = ((show == null) || (show.equals("false"))) ? 0 : 1;
		
		String latitude = olPc.get(OffLinePostcard.TAG_LATITUDE);
		if(latitude!= null)
			pc.latitude = Double.parseDouble(latitude);
		String longitude = olPc.get(OffLinePostcard.TAG_LONGITUDE);
		if(latitude!= null)
			pc.longitude = Double.parseDouble(longitude);
		
		String tags = olPc.get(OffLinePostcard.TAG_TAGS);
		IServer server = ServerFactory.getServer();
		String userID = olPc.get(OffLinePostcard.TAG_USERID);
		long userid = 0;
		if(userID != null)
			userid = Long.parseLong(olPc.get(OffLinePostcard.TAG_USERID));
		else
			userid = UserController.getLoginUser(c).UserID;
		
		String file = olPc.getImagePath();
		String updateKey = server.getUploadSKey().getUploadSKey();
		File source = new File(file);
		server.uploadFile(IServer.FILE_TYPE_POSTCARD, "image.jpg", updateKey, userid, 0, 0, options.outWidth, options.outHeight, 0, source);
		result = server.createPostcard(userid, pc.location == null? "":pc.location  ,pc.comment == null ? "":pc.comment, "", true, pc.latitude,pc.longitude, updateKey, pc.canBeFoundFlag, pc.showLocationFlag,tags == null? "" : tags);
		if(result.isSuccess())
			this.delete(name);
		
		return result;
		
	}

}
